package com.sskj.common.util;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 设备工具类
 */
public class DeviceUtil {

    private static final String DELIMITER = "#";

    /**
     * 编码：设备CODE + 通道号 → 编码字符串
     * @param deviceCode 设备编码
     * @param channel 通道ID
     */
    public static String buildStreamId(String deviceCode, int channel) {
        return buildStreamId(deviceCode, channel, null);
    }

    /**
     * 编码：设备CODE + 通道号 + 用户ID → 编码字符串
     * @param deviceCode 设备编码
     * @param channel 通道ID
     * @param userId 用户ID
     */
    public static String buildStreamId(String deviceCode, int channel, Long userId) {
        if (deviceCode == null || deviceCode.trim().isEmpty()) {
            throw new IllegalArgumentException("设备CODE不能为空");
        }

        StringBuilder sb = new StringBuilder();
        sb.append(deviceCode).append(DELIMITER).append(channel);
        if (userId != null && userId > 0) {
            sb.append(DELIMITER).append(userId);
        }

        String plainText = sb.toString();
        return Base64.getUrlEncoder().withoutPadding().encodeToString(
                plainText.getBytes(StandardCharsets.UTF_8)
        );
    }

    /**
     * 解码：从编码字符串还原为结构化数据
     *
     * @param encodedText 编码后的字符串
     * @return DecodedDeviceData 解码后的数据对象
     * @throws IllegalArgumentException 如果格式错误或参数非法
     */
    public static DecodedDeviceData decodeStreamId(String encodedText) {
        if (encodedText == null || encodedText.trim().isEmpty()) {
            throw new IllegalArgumentException("编码字符串不能为空");
        }

        try {
            byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedText);
            String plainText = new String(decodedBytes, StandardCharsets.UTF_8);
            String[] parts = plainText.split(DELIMITER);

            if (parts.length < 2) {
                throw new IllegalArgumentException("数据格式错误，至少需要设备CODE和通道号");
            }

            String deviceCode = parts[0];
            int channel = Integer.parseInt(parts[1]);
            String userId = parts.length > 2 ? parts[2] : null;

            return new DecodedDeviceData(deviceCode, channel, userId);
        } catch (Exception e) {
            throw new IllegalArgumentException("解码失败，请检查输入是否有效", e);
        }
    }




    public record DecodedDeviceData(String deviceCode, int channel, String userId) { }
}
